package com.example.vendingmachine.service.impl;

import com.example.vendingmachine.dto.UserDTO;
import com.example.vendingmachine.dto.UserQuery;
import com.example.vendingmachine.entity.User;
import com.example.vendingmachine.mapper.UserMapper;
import com.example.vendingmachine.service.UserService;
import com.example.vendingmachine.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public PageInfo<User> listUsers(UserQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return new PageInfo<>(userMapper.selectList(query));
    }

    @Override
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUser(UserDTO userDTO) {
        // 检查用户名是否已存在
        if (getUserByUsername(userDTO.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        // 加密密码
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        // 设置状态为启用
        user.setStatus("ENABLED");

        userMapper.insert(user);
        return user.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UserDTO userDTO) {
        User existUser = getUserById(userDTO.getId());

        // 如果修改了用户名,检查新用户名是否已存在
        if (!existUser.getUsername().equals(userDTO.getUsername())) {
            if (getUserByUsername(userDTO.getUsername()) != null) {
                throw new BusinessException("用户名已存在");
            }
        }

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        // 如果密码不为空,则加密新密码
        if (userDTO.getPassword() != null && !userDTO.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        }

        userMapper.update(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        User user = getUserById(id);
        // 不允许删除管理员
        if ("ADMIN".equals(user.getRole())) {
            throw new BusinessException("不能删除管理员用户");
        }
        userMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserStatus(Long id, String status) {
        User user = getUserById(id);
        // 不允许禁用管理员
        if ("ADMIN".equals(user.getRole()) && "DISABLED".equals(status)) {
            throw new BusinessException("不能禁用管理员用户");
        }
        userMapper.updateStatus(id, status);
    }
} 